﻿using System.Windows;
using System.Windows.Controls;

using Microsoft.Extensions.DependencyInjection;

using TimeSpan.Views.Windows;

namespace TimeSpan.Services;

public class NavigationService(IServiceProvider _services) : INavigationService {

    private Frame? _frame;

    public Action<Type>? OnNavigated { get; set; }

    public Frame? GetNavigationFrame() {
        return _frame;
    }

    public void Navigate<T>() where T : Page {
        Navigate(typeof(T), null);
    }

    public void Navigate<T>(object? data) where T : Page {
        Navigate(typeof(T), data);
    }

    public void Navigate(Type pageType) {
        Navigate(pageType, null);
    }

    public void Navigate(Type pageType, object? data) {
        if (_frame == null) { throw new NullReferenceException("Set navigation frame first"); }

        var viewType = pageType.GetInterface(typeof(INavigationView<>).Name);

        if (viewType != null) {
            var viewModelType = viewType.GetGenericArguments()[0];
            var viewModelInstance = _services.GetRequiredService(viewModelType);

            if (viewModelInstance is INavigationAware navAware) {
                navAware.OnNavigateTo(data);
            }
        }

        _frame.Content = _services.GetRequiredService(pageType);
        OnNavigated?.Invoke(pageType);
    }

    public void NavigateDialog<T>() where T : Window {

        var dialog = _services.GetRequiredService<T>();
        dialog.Owner = _services.GetRequiredService<MainWindow>();
        dialog.WindowStartupLocation = WindowStartupLocation.CenterOwner;

        dialog.ShowDialog();
    }

    public void SetNavigationFrame(Frame frame) {
        _frame = frame;
    }

}